import React, { useState, useEffect, useRef, Suspense } from 'react';
import { Layout, message } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import Header, { HeaderRef } from './components/Header';
import { CircleLoading } from '@/components/loading';
import mcpService from '@/api/services/mcpService';
import { CreateMcpParams } from '@/common/types';
const BasicInfo = React.lazy(() => import('./components/BasicInfo'));
const ToolsListPage = React.lazy(() => import('./components/ToolsListPage'));

interface BasicInfoRef {
  getFormData: () => BasicInfoData;
}

const { Content, Sider } = Layout;

// 工具项数据接口定义
interface ToolItem {
  name: string;
  description: string;
  inputSchema: {
    type: string;
    properties: Record<string, any>;
    required: string[];
  };
}

// BasicInfo表单数据接口定义
interface BasicInfoData {
  name?: string;
  avatar?: string;
  avatarImages?: any[];
  description?: string;
  categoryCN?: string;
  url?: string;
  templateId?: string;
  headerAuth?: Record<string, any>;
  id?: string;
  variables?: Record<string, any>;
}

const AppOrchestration: React.FC<{
  id?: string;
}> = ({ id }) => {
  const location = useLocation();
  const navigate = useNavigate();
  const headerRef = useRef<HeaderRef>(null);
  const basicInfoRef = useRef<BasicInfoRef>(null);
  const [itemData, setItemData] = useState<any>(null);
  const [toolsList, setToolsList] = useState<ToolItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [variables, setVariables] = useState({});
  const [basicInfo, setBasicInfo] = useState<BasicInfoData>({});
  const [avatarImages, setAvatarImages] = useState<string[]>([]);
  const [isFormValid, setIsFormValid] = useState<boolean>(false); // 新增：表单验证状态
  const { state } = location;

  useEffect(() => {
    const { state } = location;
    if (state?.type) {
      // 编辑状态：回显已有数据
      setItemData(state);
      setBasicInfo({
        name: state.name || '',
        avatar: state.avatar || '',
        avatarImages: state.avatarImages || [],
        description: state.description || '',
        categoryCN: state.categoryCN || '',
        url: state.url || '',
        headerAuth: state.headerAuth || {},
        id: state.id,
        variables: state.variables || {},
      });
      setToolsList(state.tools || []);
      setVariables(state.variables || {});
      setAvatarImages(state.avatarImages || []);
    } else {
      // 新增状态
      setItemData(state);
    }
  }, [location]);

  const handleSave = async (): Promise<void> => {
    try {
      const currentBasicInfo = basicInfoRef.current?.getFormData();
      console.log(currentBasicInfo, '---currentBasicInfo');
      const saveParams = {
        url: currentBasicInfo?.url || basicInfo?.url || null,
        headerAuth: currentBasicInfo?.headerAuth || basicInfo?.headerAuth || {},
        templateId: currentBasicInfo?.templateId || itemData?.templateId || undefined,
        variables: currentBasicInfo?.variables || variables || {},
        id: basicInfo?.id || undefined,
        name: currentBasicInfo?.name || basicInfo?.name || null,
        avatar: currentBasicInfo?.avatar || basicInfo?.avatar || null,
        avatarImages: currentBasicInfo?.avatarImages || avatarImages,
        description: currentBasicInfo?.description || basicInfo?.description || null,
        categoryCN: currentBasicInfo?.categoryCN || basicInfo?.categoryCN || 'location-services',
        tools: toolsList || [],
      };

      console.log('保存basicInfo:', basicInfo);
      console.log('保存参数:', saveParams);

      // 调用创建接口
      const response = await mcpService[`${saveParams?.id ? 'updateMcp' : 'createMcp'}`](saveParams as CreateMcpParams);
      if (response == null) {
        message.success('保存成功');
        // 保存成功后返回上级页面
        navigate('/worklayouts/tools/mcpCenter');
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败，请重试');
    }
  };

  const handleGetTools = (data: BasicInfoData) => {
    const { templateId, variables, url, headerAuth } = data;
    setBasicInfo(data);
    setVariables(variables || {});

    // 处理头像图片
    if (data.avatarImages && Array.isArray(data.avatarImages)) {
      setAvatarImages(data.avatarImages);
    }

    setLoading(true);
    mcpService
      .getToolsList(templateId, variables || {}, url, headerAuth)
      .then((res) => {
        console.log(res);
        setToolsList(res || []);
      })
      .catch((error) => {
        console.error('获取工具列表失败:', error);
        setToolsList([]);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <Layout className="h-screen" style={{ minWidth: '1250px' }}>
      <Header
        ref={headerRef}
        onSave={handleSave}
        McpName={itemData?.name || 'MCP工具名称'}
        isFormValid={isFormValid}
      />
      <Suspense fallback={<CircleLoading />}>
        <Layout>
          <Sider
            width="33%"
            className="m-2 mr-1 !min-w-[350px] !max-w-[600px] rounded-[12px] border border-[transparent] !bg-[#fff] bg-white"
          >
            <div className="p-4" style={{ height: 'calc(100vh - 100px)' }}>
              <Suspense fallback={<CircleLoading />}>
                <BasicInfo
                  ref={basicInfoRef}
                  itemData={itemData}
                  onSubmit={(data) => {
                    handleGetTools(data);
                  }}
                  onValidationChange={setIsFormValid}
                  className="max-h-[calc(100vh)]"
                />
              </Suspense>
            </div>
          </Sider>
          <Content className="m-2 mr-1 rounded-[12px] border border-[transparent] !bg-[#fff]">
            <Suspense fallback={<CircleLoading />}>
              <ToolsListPage
                toolsList={toolsList}
                loading={loading}
                templateId={state?.type ? itemData?.templateId : itemData?.id || undefined}
                headerAuth={itemData?.headerAuth || {}}
                variables={variables || {}}
                url={basicInfo?.url || ''}
              />
            </Suspense>
          </Content>
        </Layout>
      </Suspense>
    </Layout>
  );
};

export default AppOrchestration;
